//
//  LYRepaymentCarouseView.swift
//  LYOnlineBanking
//
//  Created by 李永彬 on 2025/7/25.
//

import UIKit

protocol LYRepaymentCarouselViewDelegate: AnyObject {
    func carouselView(_ carouselView: LYRepaymentCarouseView, didSelectItemAt index: Int, data: Receiveer)
}

class LYRepaymentCarouseView: UIView {
    
    // MARK: - Properties
    
    weak var delegate: LYRepaymentCarouselViewDelegate?
    
    private var dataSources: [Receiveer] = []
    private var timer: Timer?
    private var currentIndex: Int = 0
    
    private let collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.minimumLineSpacing = 0
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.isPagingEnabled = true
        cv.showsHorizontalScrollIndicator = false
        cv.backgroundColor = .clear
        return cv
    }()
    
    private let pageControl: UIPageControl = {
        let pc = UIPageControl()
        pc.currentPageIndicatorTintColor = .systemBlue
        pc.pageIndicatorTintColor = .lightGray
        pc.isHidden = true
        return pc
    }()
    
    // MARK: - Initialization
    
    override init(frame: CGRect = .zero) {
        super.init(frame: frame)
        commontInitSubViews()
    }
    
    func update(datas: [Receiveer]) {
        self.dataSources = datas
        self.collectionView.reloadData()
        updateSubviews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - Setup
    
    func commontInitSubViews() {
        // 配置collectionView
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(LYRepaymentCarouseCell.self, forCellWithReuseIdentifier: "LYRepaymentCarouseCell")
        addSubview(collectionView)
        
        addSubview(pageControl)
    }
    
    private func updateSubviews() {
        guard !dataSources.isEmpty else { return }
        
        // 配置pageControl
        pageControl.numberOfPages = dataSources.count
        
        // 开始自动轮播
        startAutoScroll()
    }
    
    // MARK: - Layout
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        collectionView.frame = bounds
        
        let pageControlHeight: CGFloat = 30
        pageControl.frame = CGRect(x: 0,
                                 y: bounds.height - pageControlHeight,
                                 width: bounds.width,
                                 height: pageControlHeight)
        
        // 初始位置设置为中间位置，实现无限轮播
        let middleIndex = dataSources.count * 100
        if collectionView.numberOfItems(inSection: 0) > middleIndex {
            collectionView.scrollToItem(at: IndexPath(item: middleIndex, section: 0),
                                       at: .centeredHorizontally,
                                       animated: false)
        }
    }
    
    // MARK: - Auto Scroll
    
    private func startAutoScroll() {
        timer?.invalidate()
        timer = Timer.scheduledTimer(timeInterval: 3.0,
                                   target: self,
                                   selector: #selector(autoScroll),
                                   userInfo: nil,
                                   repeats: true)
    }
    
    @objc private func autoScroll() {
        guard dataSources.count > 1 else { return }
        
        let middleIndex = dataSources.count * 100
        let nextIndex = currentIndex + 1
        
        if collectionView.numberOfItems(inSection: 0) > nextIndex {
            collectionView.scrollToItem(at: IndexPath(item: nextIndex, section: 0),
                                       at: .centeredHorizontally,
                                       animated: true)
        }
        
        // 如果接近边界，重置到中间位置
        if nextIndex > middleIndex + dataSources.count - 1 {
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                
                if self.collectionView.numberOfItems(inSection: 0) > middleIndex {
                    self.collectionView.scrollToItem(at: IndexPath(item: middleIndex, section: 0),
                                                   at: .centeredHorizontally,
                                                   animated: false)
                }
            }
        }
    }
    
    private func stopAutoScroll() {
        timer?.invalidate()
        timer = nil
    }
    
    // MARK: - Public Methods
    
    func setDatas(_ datas: [Receiveer]) {
        self.dataSources = datas
        pageControl.numberOfPages = datas.count
        collectionView.reloadData()
        
        // 重置位置
        let middleIndex = datas.count * 100
        collectionView.scrollToItem(at: IndexPath(item: middleIndex, section: 0),
                                    at: .centeredHorizontally,
                                    animated: false)
    }
    
    // MARK: - Deinit
    
    deinit {
        stopAutoScroll()
    }
}

// MARK: - UICollectionViewDataSource & UICollectionViewDelegate

extension LYRepaymentCarouseView: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataSources.isEmpty ? 0 : dataSources.count * 200 // 足够大的数字实现无限轮播
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LYRepaymentCarouseCell", for: indexPath) as! LYRepaymentCarouseCell
        let index = indexPath.item % dataSources.count
        let receiveer = dataSources[index]
        cell.setData(data: receiveer)
        cell.delegate = self
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return bounds.size
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let index = indexPath.item % dataSources.count
        let receiveer = dataSources[index]
        delegate?.carouselView(self, didSelectItemAt: index, data: receiveer)
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        guard !dataSources.isEmpty else { return }
        
        let pageWidth = scrollView.frame.width
        let currentPage = Int((scrollView.contentOffset.x + pageWidth / 2) / pageWidth) % dataSources.count
        pageControl.currentPage = currentPage
        currentIndex = Int(scrollView.contentOffset.x / pageWidth)
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        stopAutoScroll()
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        startAutoScroll()
    }
}

extension LYRepaymentCarouseView: LYRepaymentCarouseCellDelegate {
    func didClickRepaymentButton(data: Receiveer) {
        
    }
}

